$(function(){

	var curEditDictId = null;

	function DictCreateModal(modalEle) {
		var self = this;
		self.$ele = modalEle;
		$('.save-btn',self.$ele).on('click',function(){
			self._onSave();
		});	
		$('.cancel-btn',self.$ele).on('click',function() {
			self._onCancel();
		});	
		self._initModal();
		self._initValidate();
	}

	DictCreateModal.prototype = {
		constructor: DictCreateModal,
		$ele: null,		
		$permissionBox: null,
		$selectBox: null,
		$validater: null,
		tagBox: null,
		_initModal: function () {
			$(this.$ele).modal({
				backdrop: 'static',
				keyboard: false,	
				show: false
			});
		},
		_initValidate: function() {
			this.validater = $('#dict-create-form').validate({
				rules: {},
				messages:
						{},
				showErrors: function(errorMap, errorList){
								if(errorList.length > 0) {
									var error = errorList[0];
									$(error.element).parent().addClass('has-error');
									$('#dict-create-msg').show().find('p').text(error.message);
								}
							},
				onkeyup: function(ele) {
							$('#dict-create-msg').hide();
							$(ele).parent().removeClass('has-error');
						 },
				success: function(label,ele) {
							 console.log(lable);
							 console.log(ele);
						 },
				submitHandler: function(){
							$('#dict-create-box .overlay').show();
							saveDict();
						   }
				
			});
	   },
		getCheckedIdArr: function(){
			return this.tagBox.getCheckedTagIdArray();
		},
		_onCancel: function() {
			$(this.$ele).modal('hide');
		},
		_onSave: function() {
			$('form',this.$ele).submit();
		},
		_reset: function () {
			$('#dict-create-modal input:text').each(function(){
				$(this).val('');
			});
			$('#dict-create-msg').hide();
			$('.has-error').removeClass('has-error');
			$('#dict-create-box .overlay').hide();
		},
		close: function () {
			$(this.$ele).modal('hide');
		},
		open: function (dictInfo) {
			this._reset();
			if(dictInfo) {
				$('.dict-create-title',this.$ele).html('编辑字典');
				for(var key in dictInfo) {
					$('input[name="'+key+'"]',this.$ele).val(dictInfo[key]);
				}
			} else {
				$('.dict-create-title',this.$ele).html('新建字典');
				$('#pid').val(1) ;
				$('#enable').val("1");
			}
			$(this.$ele).modal('show');
		}
	};

	var dictCreater = new DictCreateModal($('#dict-create-modal'));

    /**
	 * 增加按钮
     */
	$('#dict-create-btn').on('click',function(){
		curEditDictId = null;
		dictCreater.open();
	});

    /**
     * 修改按钮
     */
    $('#dict-edit-btn').on('click',function(){

        var id = getEditCheckedId();
        if(id != 0){
            curEditDictId = id;
			setEditModel(curEditDictId)
		}

    });

    /**
	 * 获取选中id
     */
    function getEditCheckedId(){

        var id = 0;
        //选中个数
        var size = $(".icheckbox_flat-blue.checked").length ;
        if(size == 0){
            alerting({
                msg: '请选择一条要修改的字典项？',
                title: function(){
                    return '友情提示';
                }
            });
            return id ;
        }else if(size > 1){

            alerting({
                msg: '对不起，只能选择一条字典项修改？',
                title: function(){
                    return '友情提示';
                }
            });
            return id ;
		}
        alert($(".icheckbox_flat-blue.checked").children('input').val());
        return  $(".icheckbox_flat-blue.checked").children('input').val() ;
	}

    /**
     * 刷新按钮
     */
    $('#dict-refresh-btn').on('click',function(){

    	refresh();
    });
	function refresh(){
        window.location.reload();
	}

    /**
	 * 编辑按钮
     */
	$('.edit-btn').on('click',function(){

		var $tr = $(this).parents('tr');
		curEditDictId = $tr.attr('data-uid');
        setEditModel(curEditDictId)
	});
    /**
	 * 回填修改model值
     * @param curEditDictIds
     */
	function setEditModel(curEditDictId){

        cAjax({
            url: '/sysdict/editModel',
            type: 'get',
            data: {
                id: curEditDictId
            },
            success: function(obj) {
                console.log(obj);
                var dictInfo = obj.data;
                $("#pid").val(dictInfo.pid);
                $("#enable").val(dictInfo.enable);
                dictCreater.open(dictInfo);
            },
            error: function(obj) {
                console.log(obj);
            }
        });
	}

    /**
	 * 增加or修改提交
     */
	function saveDict() {
		var data = {},
			url = '';
		$('#dict-create-modal input:text').each(function(){
			var $this = $(this);
			data[$this.attr('name')] = $.trim($this.val());
		});
		$('#dict-create-modal select').each(function(){
			var $this = $(this);
			data[$this.attr('name')] = $.trim($this.val());
		});
		if(curEditDictId == null) {
			url = '/sysdict/insert';
		} else {
			data['id'] = curEditDictId;
			url = '/sysdict/edit';
		}
		console.log(data);
		dictCreater.close();

		cAjax({
			url: url,
			data: data,
			success: function(obj) {
				console.log(obj);
				greeting({
					msg: obj.msg,
					confirm: function(){
						window.location.reload();
					}

				});
			},
			error: function(obj){
				console.log(obj);
		   }
		});
	}

    /**
	 * 批量删除按钮
	 *
     */
    var ids = '';
    $('#dict-delete-btn').on('click',function(){

    	   ids = getDeleteCheckedIds();
    	   alert(ids);
    	   if(ids != ''){
               deleteData(ids);
		   }
    });
    /**
     * 获取选中id
     */
    function getDeleteCheckedIds(){
        ids = '';
        //选中个数
        var size = $(".icheckbox_flat-blue.checked").length ;
        if(size == 0){
            alerting({
                msg: '请选择要删除的字典项？',
                title: function(){
                    return '友情提示';
                }
            });
            return ids ;
        }
        //拼接id值
        $(".icheckbox_flat-blue.checked").each(function(){
            var $this = $(this);
            ids += $this.children('input').val() +',';
        });
        return ids ;
    }


    /**
	 * 单个删除操作
     */
	$('.dict-del-btn').on('click',function(){
		var $this = $(this);
        ids = $this.parents('tr').attr('data-uid')+',';
        deleteData(ids);
	});

    /**
	 * 删除提交
     */
    function deleteData(ids){

    	var msg = '确定要删除这条字典吗？';
        var arry = ids.split(',');
        if(arry.length >1){msg = '确定要删除这些字典吗？';}
        actionConfirm({
            msg: msg,
            confirm: function() {
                cAjax({
                    url:'/sysdict/deleteByIds',
                    type:'post',
                    data:{ids:ids },
                    success:function(obj){
                        console.log(obj);
                        greeting({
                            msg: obj.msg,
                            confirm: function(){
                                window.location.reload();
                            }
                        });
                        // $this.parents('tr').addClass('deleted');
                        // $this.parent().html('<span class="label label-warning">已删除</span>');
                    },
                    error: function(obj) {
                        console.log(obj);
                        greeting({
                            msg: obj.msg
                        })
                    }
                });
            }
        });
	}
});
